<template>
  <div class="role-management">
    <!-- 搜索区域 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item :label="$t('page.system.role.name')">
          <el-input
            v-model="searchForm.name"
            :placeholder="$t('page.system.role.name')"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item :label="$t('page.system.role.roleKey')">
          <el-input
            v-model="searchForm.roleKey"
            :placeholder="$t('page.system.role.roleKey')"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item :label="$t('page.system.role.status')">
          <el-select
            v-model="searchForm.status"
            :placeholder="$t('page.system.role.status')"
            clearable
            style="width: 120px"
          >
            <el-option :label="$t('page.system.role.normal')" :value="0" />
            <el-option :label="$t('page.system.role.disabled')" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            {{ $t('page.system.role.search') }}
          </el-button>
          <el-button @click="handleReset">
            {{ $t('page.system.role.reset') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">
        + {{ $t('page.system.role.add') }}
      </el-button>
      <el-button
        type="danger"
        :disabled="selectedRows.length === 0"
        @click="handleBatchDelete"
      >
        {{ $t('page.system.role.batchDelete') }}
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        prop="id"
        label="ID"
        width="80"
        align="center"
      />
      <el-table-column
        prop="name"
        :label="$t('page.system.role.name')"
        min-width="120"
      />
      <el-table-column
        prop="roleKey"
        :label="$t('page.system.role.roleKey')"
        min-width="120"
      />
      <el-table-column
        prop="status"
        :label="$t('page.system.role.status')"
        width="100"
        align="center"
      >
        <template #default="{ row }">
          <el-tag :type="row.status === 0 ? 'success' : 'danger'">
            {{ row.status === 0 ? $t('page.system.role.normal') : $t('page.system.role.disabled') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createdTime"
        :label="$t('page.system.role.createdTime')"
        width="180"
        align="center"
      />
      <el-table-column
        :label="$t('page.system.role.operation')"
        width="250"
        align="center"
        fixed="right"
      >
        <template #default="{ row }">
          <el-button
            size="small"
            type="primary"
            text
            @click="handleEdit(row)"
          >
            {{ $t('page.system.role.edit') }}
          </el-button>
          <el-button
            size="small"
            type="warning"
            text
            @click="handleAssignPermission(row)"
          >
            {{ $t('page.system.role.assignPermission') }}
          </el-button>
          <el-button
            size="small"
            type="success"
            text
            @click="handleRolePermissionAssociation(row)"
          >
            权限关联
          </el-button>
          <el-button
            size="small"
            type="info"
            text
            @click="handleViewUsers(row)"
          >
            {{ $t('page.system.userRole.userList') }}
          </el-button>
          <el-button
            size="small"
            :type="row.status === 0 ? 'warning' : 'success'"
            text
            @click="handleStatusChange(row)"
          >
            {{ row.status === 0 ? $t('page.system.role.disable') : $t('page.system.role.enable') }}
          </el-button>
          <el-button
            size="small"
            type="danger"
            text
            @click="handleDelete(row)"
          >
            {{ $t('page.system.role.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="paginationData.pageNo"
        v-model:page-size="paginationData.pageSize"
        :total="paginationData.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 角色表单弹窗 -->
    <RoleForm
      v-model:visible="formVisible"
      :form-data="currentRole"
      :is-edit="isEdit"
      @submit="handleFormSubmit"
    />

    <!-- 权限分配弹窗 -->
    <RolePermissionModal
      v-model:visible="permissionVisible"
      :role-id="currentRoleId"
      @submit="handlePermissionSubmit"
    />

    <!-- 角色权限关联弹窗 -->
    <RolePermissionAssociationModal
      v-model:visible="associationModalVisible"
      :role-id="currentRoleForAssociation?.id || 0"
      :role-name="currentRoleForAssociation?.name || ''"
      @submit="handleAssociationSubmit"
    />

    <!-- 角色用户列表弹窗 -->
    <RoleUsersModal
      v-model:visible="usersVisible"
      :role="currentRoleForUsers"
      :all-users="allUsers"
      @refresh="handleUsersRefresh"
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElPagination,
  ElSelect,
  ElTable,
  ElTableColumn,
  ElTag,
} from 'element-plus';

import type { Role, RoleFormData, RoleListParams } from '#/api/system/role';
import {
  changeRoleStatusApi,
  deleteRoleApi,
  getRoleListApi,
} from '#/api/system/role';
import type { UserInfo } from '#/api/system/userRole';
import { getAllUsersApi } from '#/api/system/user';
import { $t } from '#/locales';

import RoleForm from './components/RoleForm.vue';
import RolePermissionModal from './components/RolePermissionModal.vue';
import RolePermissionAssociationModal from './components/RolePermissionAssociationModal.vue';
import RoleUsersModal from './components/RoleUsersModal.vue';

// 搜索表单
const searchForm = reactive<Partial<RoleListParams>>({
  name: '',
  roleKey: '',
  status: undefined,
});

// 分页数据
const paginationData = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});

// 表格数据
const tableData = ref<Role[]>([]);
const loading = ref(false);
const selectedRows = ref<Role[]>([]);

// 表单弹窗
const formVisible = ref(false);
const currentRole = ref<Partial<RoleFormData>>({});
const isEdit = ref(false);

// 权限分配弹窗
const permissionVisible = ref(false);
const currentRoleId = ref<number>(0);

// 角色权限关联弹窗
const associationModalVisible = ref(false);
const currentRoleForAssociation = ref<Role | null>(null);

// 用户列表弹窗
const usersVisible = ref(false);
const currentRoleForUsers = ref<Role | null>(null);
const allUsers = ref<UserInfo[]>([]);

// 获取角色列表
const getRoleList = async () => {
  loading.value = true;
  try {
    const params: RoleListParams = {
      pageNo: paginationData.pageNo,
      pageSize: paginationData.pageSize,
      ...searchForm,
    };
    const data = await getRoleListApi(params);
    tableData.value = data.result;
    paginationData.total = data.total;
  } catch (error) {
    console.error('获取角色列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  paginationData.pageNo = 1;
  getRoleList();
};

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key as keyof typeof searchForm] = undefined;
  });
  searchForm.name = '';
  searchForm.roleKey = '';
  handleSearch();
};

// 新增角色
const handleAdd = () => {
  currentRole.value = {
    name: '',
    roleKey: '',
    status: 0,
  };
  isEdit.value = false;
  formVisible.value = true;
};

// 编辑角色
const handleEdit = (row: Role) => {
  currentRole.value = { ...row };
  isEdit.value = true;
  formVisible.value = true;
};

// 删除角色
const handleDelete = async (row: Role) => {
  try {
    await ElMessageBox.confirm(
      $t('page.system.role.message.deleteConfirm'),
      $t('page.system.role.delete'),
      {
        type: 'warning',
      }
    );
    await deleteRoleApi(row.id.toString());
    ElMessage.success($t('page.system.role.message.deleteSuccess'));
    getRoleList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除角色失败:', error);
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) return;
  
  try {
    await ElMessageBox.confirm(
      $t('page.system.role.message.batchDeleteConfirm'),
      $t('page.system.role.batchDelete'),
      {
        type: 'warning',
      }
    );
    const ids = selectedRows.value.map(row => row.id).join(',');
    await deleteRoleApi(ids);
    ElMessage.success($t('page.system.role.message.deleteSuccess'));
    getRoleList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除角色失败:', error);
    }
  }
};

// 状态变更
const handleStatusChange = async (row: Role) => {
  const newStatus = row.status === 0 ? 1 : 0;
  const action = newStatus === 0 ? $t('page.system.role.enable') : $t('page.system.role.disable');
  
  try {
    await ElMessageBox.confirm(
      $t('page.system.role.message.statusChangeConfirm', { action }),
      $t('page.system.role.status'),
      {
        type: 'warning',
      }
    );
    await changeRoleStatusApi({ id: row.id, status: newStatus });
    ElMessage.success($t('page.system.role.message.statusChangeSuccess'));
    getRoleList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('修改角色状态失败:', error);
    }
  }
};

// 分配权限
const handleAssignPermission = (row: Role) => {
  currentRoleId.value = row.id;
  permissionVisible.value = true;
};

// 角色权限关联
const handleRolePermissionAssociation = (row: Role) => {
  currentRoleForAssociation.value = row;
  associationModalVisible.value = true;
};

// 查看用户列表
const handleViewUsers = (row: Role) => {
  currentRoleForUsers.value = row;
  usersVisible.value = true;
};

// 表格选择变更
const handleSelectionChange = (selection: Role[]) => {
  selectedRows.value = selection;
};

// 分页大小变更
const handleSizeChange = (size: number) => {
  paginationData.pageSize = size;
  getRoleList();
};

// 分页变更
const handleCurrentChange = (page: number) => {
  paginationData.pageNo = page;
  getRoleList();
};

// 表单提交
const handleFormSubmit = () => {
  formVisible.value = false;
  getRoleList();
};

// 权限提交
const handlePermissionSubmit = () => {
  permissionVisible.value = false;
  ElMessage.success($t('page.system.role.message.assignPermissionSuccess'));
};

// 权限关联提交成功
const handleAssociationSubmit = () => {
  associationModalVisible.value = false;
  getRoleList(); // 刷新角色列表
};

// 用户刷新回调
const handleUsersRefresh = () => {
  // 可以在这里刷新角色列表，如果需要更新角色的用户计数等信息
  getRoleList();
};

// 获取所有用户
const getAllUsers = async () => {
  try {
    console.log('开始获取用户列表...');
    const users = await getAllUsersApi();
    console.log('获取到的用户列表:', users);
    console.log('用户列表数据类型:', Array.isArray(users) ? '数组' : typeof users);
    allUsers.value = users || [];
    console.log('allUsers.value 已更新，数量:', allUsers.value.length);
  } catch (error) {
    console.error('获取用户列表失败:', error);
    console.error('错误详情:', error);
    // 确保即使失败也设置为空数组
    allUsers.value = [];
  }
};

// 初始化
onMounted(() => {
  getRoleList();
  getAllUsers(); // 重新添加获取用户列表，用于分配用户功能
});
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.search-form {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 
 